﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Internal
{
    /// <summary>
    /// 为给定的key延迟创建（缓存）value值。如果创建值失败（具有错误），在获取值时将抛出异常
    /// </summary>
    public abstract class FailableCache<K, V>
        where K : class
        where V : class
    {
        private readonly ConcurrentMap<K, object> delegatee;

        public FailableCache()
        {
            delegatee = new MapMaker().MakeComputingMap<K, object>((k) =>
            {
                Errors errors = new Errors();
                V result = null;
                try
                {
                    result = Create(k, errors);
                }
                catch (ErrorsException e)
                {
                    errors.Merge(e.Errors);
                }
                return errors.HasErrors ? (object)errors : result;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        /// <exception cref="ErrorsException"></exception>
        protected abstract V Create(K key, Errors errors);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        /// <exception cref="ErrorsException"></exception>
        public V Get(K key, Errors errors)
        {
            object resultOrError = delegatee[key];
            if (resultOrError is Errors)
            {
                errors.Merge((Errors)resultOrError);
                throw errors.ToException();
            }
            else
            {
                V result = (V)resultOrError;
                return result;
            }
        }

        public bool Remove(K key)
        {
            return delegatee.Remove(key) != null;
        }
    }
}
